package core

import (
	"net/http"

	"github.com/goccy/go-json"

	"codeberg.org/vnpower/pixivfe/v2/audit"
	"codeberg.org/vnpower/pixivfe/v2/server/session"
)

type CommentService interface {
	GetComments(auditor *audit.Auditor, r *http.Request, id string) ([]Comment, error)
}

type commentService struct {
	getCommentsURL func(id string) string
}

func (cs *commentService) GetComments(auditor *audit.Auditor, r *http.Request, id string) ([]Comment, error) {
	var body struct {
		Comments []Comment `json:"comments"`
	}

	url := cs.getCommentsURL(id)

	resp, err := API_GET_UnwrapJson(r.Context(), auditor, url, "", r.Header)
	if err != nil {
		return nil, err
	}

	resp, err = session.ProxyImageUrl(r, resp)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal([]byte(resp), &body)
	if err != nil {
		return nil, err
	}

	return body.Comments, nil
}

func NewCommentService(getCommentsURL func(id string) string) CommentService {
	return &commentService{
		getCommentsURL: getCommentsURL,
	}
}
